//
//  ProvinceCtrl.m
//  diaoyuren
//
//  Created by 钓鱼人 on 16/2/29.
//  Copyright © 2016年 game. All rights reserved.
//

#import "ProvinceCtrl.h"
#import "FMDatabase.h"
#import "CGFdbmBase.h"
#import "CityModel.h"
#import "Region_cityCtl.h"
#import "AreaControl.h"
#import "CitySerchBar.h"
#import "WetherModel.h"
#import "WeathCitysCtrl.h"

@interface ProvinceCtrl ()<CitySearchBarDeleget,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic,strong) NSMutableArray *provinceAry;
@property (nonatomic,strong) CitySerchBar *searchBar;
@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIView *NavbacView;

@property (nonatomic,assign) BOOL isSearch;

@end

@implementation ProvinceCtrl

-(NSMutableArray *)provinceAry{
    if (!_provinceAry) {
        _provinceAry  = [NSMutableArray array];
    }
    return _provinceAry;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self NavSet];
}

-(void)NavSet{

    self.navigationController.navigationBar.hidden = YES;
    
    self.NavbacView = [self Linview:CGRectMake(0, 0, SCREEN_WIDTH, 64) BackgroundColor:[UIColor whiteColor] AddView:self.view];
    
    self.searchBar = [[CitySerchBar alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    self.searchBar.Maideleget = self;
    [self.NavbacView addSubview:self.searchBar];
}

-(void)CancelClick{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)SearchReault:(NSArray *)rearultAry AndIsAction:(BOOL)isaction{
    if (isaction) {
        
        [self.provinceAry removeAllObjects];
        [self.provinceAry addObjectsFromArray:rearultAry];
        
    }else{
        
        [self.provinceAry removeAllObjects];
    self.provinceAry = [[CGFdbmBase SeachWhithPath:@"diaoyur_city" AndTableName:@"region_province" IdStrName:@"name"] mutableCopy];
    }
    
    self.isSearch = isaction;
    
    [self.tableView reloadData];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
 
    self.provinceAry = [[CGFdbmBase SeachWhithPath:@"diaoyur_city" AndTableName:@"region_province" IdStrName:@"name"] mutableCopy];
    
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, screen_height) style:UITableViewStylePlain];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.tableFooterView = [UIView new];
    [self.view addSubview:self.tableView];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.provinceAry.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    
    if (!self.isSearch) {
         cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    
    cell.textLabel.text = self.provinceAry[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:SCREEN_WIDTH*0.04];
    cell.textLabel.alpha = 0.7;
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (self.isSearch) {
        
        NSString *selectString= [NSString stringWithFormat:@"SELECT * FROM region_area WHERE name = '%@'",cell.textLabel.text];
        
        NSDictionary *dic = [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_area" SelectSting:selectString].firstObject;
        
        if (!dic) {
            selectString= [NSString stringWithFormat:@"SELECT * FROM region_city WHERE name = '%@'",cell.textLabel.text];
            
           dic = [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_city" SelectSting:selectString].firstObject;
        }
        
        CityModel *model = [[CityModel alloc]initWithDictionary:dic error:nil];
        WeathCitysCtrl *cityCtl = [self.navigationController.viewControllers objectAtIndex:2];
        
       
        
        if (cityCtl.cityArys.count==0) {
            [cityCtl.cityArys addObject: dic];
            [self AchiveWeatherDataWhithCityName:model.name AndCode:model.code AndCtrl:cityCtl];
        }
        
        NSInteger count = 0;
     
        for (NSDictionary *dic in cityCtl.cityArys) {
            if ([dic[@"name"] isEqualToString:model.name]) {
                
                count = 2;
          
            }
            
    }
        
        if (count!=2) {
            [cityCtl.cityArys addObject:dic];
            [self AchiveWeatherDataWhithCityName:model.name AndCode:model.code AndCtrl:cityCtl];
        }
        
        [cityCtl setCityArys:cityCtl.cityArys ];
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
        
    }else{
    
        NSString *selectString= [NSString stringWithFormat:@"SELECT * FROM region_province WHERE name = '%@'",cell.textLabel.text];
        NSDictionary *dic = [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_province" SelectSting:selectString].firstObject;
        CityModel *model = [[CityModel alloc]initWithDictionary:dic error:nil];
        
        /**
         *  如果是直辖市  就直接跳转到最后一个页面
         */
        if ([model.name isEqualToString:@"北京市"]||[model.name isEqualToString:@"天津市"]||[model.name isEqualToString:@"上海市"]||[model.name isEqualToString:@"重庆市"]) {
            AreaControl *regist = [AreaControl new];
            
            /**
             *  直辖市的城市code 比省份里的 code  多100
             */
            NSInteger code = model.code.integerValue+100;
            regist.code = [NSString stringWithFormat:@"%ld",(long)code];
            NSString *selectString= [NSString stringWithFormat:@"SELECT * FROM region_city WHERE code = %ld",(long)code];
            NSDictionary *dic =[CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_city" SelectSting:selectString].firstObject;
            regist.ares = [NSMutableArray arrayWithObject:dic];
            [self.navigationController pushViewController:regist animated:YES];
            
        }else{
            
            Region_cityCtl *regist = [Region_cityCtl new];
            regist.provincecode = model.code;
            [self.navigationController pushViewController:regist animated:YES];
        }
    }
}

//获取天气数据
-(void)AchiveWeatherDataWhithCityName:(NSString *)cityname AndCode:(NSString *)citycode AndCtrl:(WeathCitysCtrl *)cityCtl{
    [[Manager sharedManager]RequestWhithURL:[NSString stringWithFormat:weathUrl,citycode] AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        WetherModel *model = [[WetherModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
        
        if (model) {
            [cityCtl.cityDatadic addEntriesFromDictionary:@{cityname:model}];
        }else{
            __block NSString *dicKey;
            [cityCtl.cityDatadic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                dicKey = key;
                if (dicKey.length!=0) {
                    *stop = YES;
                }
            }];
            
            [cityCtl.cityDatadic addEntriesFromDictionary:@{cityname:cityCtl.cityDatadic[dicKey]}];
        }
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return SCREEN_HEIGHT*0.07;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    [self.searchBar resignFirstResponder];
    self.searchBar.cancelButton.enabled = YES;
}
@end